默认的,没有被@DateTimeFormat
注解日期和时间字段会被以DateFormat.SHORT
的风格。如果你愿意,你可以定义自己的全局样式。
你需要确保Spring不会注册默认的formatter,并且手动注册所有的formatters。用org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar
还是org.springframework.format.datetime.DateFormatterRegistrar
取决于你是否使用了Joda Time库。
比如,下面的Java配置将会注册一个全局的yyyyMMdd
的格式。这个例子没有依赖Joda Time库:
@Configuration
public class AppConfig {
@Bean
public FormattingConversionService conversionService() {
// Use the DefaultFormattingConversionService but do not register defaults
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);
// Ensure @NumberFormat is still supported
conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
// Register date conversion with a specific global format
DateFormatterRegistrar registrar = new DateFormatterRegistrar();
registrar.setFormatter(new DateFormatter("yyyyMMdd"));
registrar.registerFormatters(conversionService);
return conversionService;
}
}
如果你偏爱基于XML的配置,你可以使用FormattingConversionServiceFactoryBean
。下面这个例子用了Joda Time:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="registerDefaultFormatters" value="false" />
<property name="formatters">
<set>
<bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" />
</set>
</property>
<property name="formatterRegistrars">
<set>
<bean class="org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar">
<property name="dateFormatter">
<bean class="org.springframework.format.datetime.joda.DateTimeFormatterFactoryBean">
<property name="pattern" value="yyyyMMdd"/>
</bean>
</property>
</bean>
</set>
</property>
</bean>
</beans>
Joda Time 提供了不同的类型来分别表示
date
,time
和date-time
。JodaTimeFormatterRegistrar
中的dateFormatter
,timeFormatter
和dateTimeFormatter
属性分别被用来对应的属性。DateTimeFormatterFactoryBean
提供了简便的方式去创建formatters。
如果你在使用Spring MVC,请记住直接的配置要是用的conversion service。这意味着在基于Java的@Configuration
中,要继承WebMvcConfigurationSupport
类并且覆盖mvcConversionService()
方法。基于XML的配置,你需要使用mvc:annotation-driven
的'cnversion-service'
元素。详见21.6.3节,"Conversion and Formatting"。